package com.framework.boc.admin.security.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
public class MyUserDetailsService implements UserDetailsService {

    private List<User> users = new ArrayList<>();

    {
        users.add(new User("admin", "123456", Arrays.asList(new SimpleGrantedAuthority("ROLE_admin"))));
        users.add(new User("user", "123456", Arrays.asList(new SimpleGrantedAuthority("user"))));
    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Optional<User> userOptional = users.stream().
                filter(user -> StringUtils.equals(userName, user.getUsername()))
                .findFirst();
        if (userOptional.isPresent()) {
            return userOptional.get();
        }
        throw new UsernameNotFoundException("用户未找到");
    }
}
